<?php
error_reporting(E_ALL);

include('files/configure.php');
include('files/ftp.php');
include('files/class.db.php');
include(ALARM_FILE);
include('/var/www/Spy_embankment/files/php/class.archivio.writer.php');

/*
 * Ultima data del file processato 
 * WHERE alarm_id = 1 
 */
function statusTask()
{
    $msql  = new Db;
    $msql->connect();

    $arr_data=$msql->execute_select("SELECT data FROM data_schedulazione WHERE id=1;");
    $ora_schedulazione=$arr_data[0][0];
    
    $arr_data=$msql->execute_select("SELECT InsertDate FROM communications where alarm_id= 1 order by InsertDate desc limit 1;");
    $data_last_send=strtotime( $arr_data[0][0] );

    $diff=(time() - $data_last_send);
    $ore_sec=(3600 * $ora_schedulazione)-600; //600 10 minuti di margine
    echo $arr_data[0][0]." ".time()." $diff > $ore_sec \n";
    if( $diff >= $ore_sec)
    {
        echo "$diff > $val \n";
        $alarm=new Alarm();
        $alarm->SendStatusSistem($alarm->SMS);
        $alarm->SendStatusSistem($alarm->EMAIL);
        $alarm->SendStatusSistem($alarm->FAX);
    }
    $msql->disconnettiDB();
}

function selectSezioni($sezioni)
{
    $string="P1Pz01,P1Rx,";
    $string.="P2Pz02,P2Pz03,P2Rx,";
    $string.="P3Pz04,P3Pz05,P3Rx,";
    $string.="P4Pz06,P4Pz07,P4Pz08,P4Rx,";
    $string.="P5Pz09,P5Pz10,P5Rx,";
    $string.="P6Pz11,P6Pz12,P6Pz13,P6Rx,";
    $string.="P7Pz14,P7Pz15,P7Pz16,P7Rx,";
    $string.="P8Pz17,P8Pz18,P8Pz19,P8Rx,";
    $string.="P9Pz20,P9Pz21,P9Pz22,P9Rx,";
    $string.="P10Pz23,P10Pz24,P10Pz25,P10Rx,";
    $string.="P11Pz26,P11Pz27,P11Pz28,P11Rx,";
    $string.="P12Pz29,P12Pz30,P12Rx,";
    $string.="P13Pz31,P13Pz32,P13Pz33,P13Rx,";
    $string.="P14Pz34,P14Pz35,P14Pz36,P14Rx,";
    $string.="P15Pz37,P15Rx";

    return $string;
    
}

function MakeWriterArchivio($start_data,$end_data,$sezioni)
{   
    //global $MYSQL_SEZIONI;
    $tring_sez=selectSezioni($sezioni);
    $s_query = "SELECT data,$tring_sez FROM dati_impianto where data >= '$start_data' and data <= '$end_data';";
   // echo $s_query;
    $fw = new ArchivioWriter($start_data,$end_data,$tring_sez,PATH_ARCHIVIO);
    $search=array(' ',':');
    $nome_file=str_replace($search, '-','archivioFrom'.$start_data.'To'.$end_data);
    $archivio_dir=$fw->writeFile($s_query,$nome_file);
    if($archivio_dir)
        $fw->Zip($archivio_dir,$archivio_dir,false);
    //rmdir(realpath("$dir_arch/$archivio_dir"));
    $dir=PATH_ARCHIVIO.$nome_file;
    return array("result"=>$archivio_dir,"dir"=>$dir);
}

function MakeWriterRasponi($start_data,$end_data)
{   
    //global $MYSQL_SEZIONI;
    $s_query = "SELECT data,valore FROM rasponi where data >= '$start_data' and data <= '$end_data';";
   // echo $s_query;
    $fw = new ArchivioWriter($start_data,$end_data,"",PATH_ARCHIVIO);
    $search=array(' ',':');
    $nome_file=str_replace($search, '-','archivio_rasponi'.$start_data.'To'.$end_data);
    $archivio_dir=$fw->writeFile($s_query,$nome_file);
    if($archivio_dir)
        $fw->Zip($archivio_dir,$archivio_dir,false);
    //rmdir(realpath("$dir_arch/$archivio_dir"));
    $dir=PATH_ARCHIVIO.$nome_file;
    return array("result"=>$archivio_dir,"dir"=>$dir);
}

function checkArchivioHasDeleted($nome_tab)
{
    $DATI_IMPIANTO='dati_impianto';
    $RASPONI='rasponi';
    
    $ret=TRUE;
    $msql_new  = new Db;
    $msql_new->connect();
    
    $arr_data=$msql_new->execute_select("SELECT * FROM delete_dati where nome_tab = '$nome_tab'"); 
    if(count($arr_data[0]) > 0)
    { //non sono stati archiviati i dati vecchi
      $start_data=$arr_data[0][1];
      $start_end=$arr_data[0][2];
      $checksum=$arr_data[0][4];
      $file=$arr_data[0][5];
      $stringa="TUTTE LE SEZIONI";
      if($nome_tab == $RASPONI)
          $stringa="RASPONI";
      $alarm=new Alarm();
      $alarm->SendArchivioSistem($file,$start_data,$start_end,$checksum,$stringa);
      
      $ret=FALSE;
           
    }
    
    return ($ret);
}

function makeArchivio()
{
    $msql_new  = new Db;
    $msql_new->connect();
    
    
    $arr_data=$msql_new->execute_select("SELECT data FROM dati_impianto order by data asc limit 1;"); //data piu vecchia in DB
    $start_data= $arr_data[0][0];
    $lastDataDb=strtotime( $start_data );
    $arr_data=$msql_new->execute_select("SELECT data FROM dati_impianto order by data desc limit 1;"); //data piu recente in DB
    $NowDataDb=strtotime( $arr_data[0][0] );

    $arr_data=$msql_new->execute_select("SELECT data FROM data_schedulazione where id=2;"); //data piu recente in DB
    $giorni=$arr_data[0][0];
    
    $msql_new->disconnettiDB();
    
    $diff_giorni=($NowDataDb - $lastDataDb)/ 86400;
    echo "GIORNI $giorni $diff_giorni\n";
    $ANNO=($giorni * 24 * 60 * 60) / 2; //Meta del periodo selezionato
    //l'ultima data da eliminare dal dato piu vecchio fino alla data inserita diviso 2
    $data_year_ago_sec=($NowDataDb - $ANNO);
    
    
    $data_sec=strftime('%Y-%m-%d %H:%M:%S',$lastDataDb);
    echo $data_sec."\n";
    $data_year_ago=strftime('%Y-%m-%d %H:%M:%S',$data_year_ago_sec);
    echo $data_year_ago."-------\n";

   
    if($diff_giorni >= $giorni)
    {
        if(checkArchivioHasDeleted("dati_impianto"))
        {
            $archivio_dir=MakeWriterArchivio($start_data,$data_year_ago,$sezioni);

            if($archivio_dir['result'])
            {
               $file=$archivio_dir['dir'];
               chown("$file.zip",'www-data');
               chmod("$file.zip", 0777);
               $checksum = sha1($start_data.$data_year_ago."dati_impianto"); 
               $alarm=new Alarm();
               $alarm->SendArchivioSistem("$file.zip",$start_data,$data_year_ago,$checksum,"TUTTE LE SEZIONI");
               echo "----------------------$file\n\n";

               $query="INSERT INTO delete_dati (nome_tab,data_start,data_end,checksum,path_file) VALUES ('dati_impianto','$start_data','$data_year_ago','$checksum','$file.zip'); "; 
               echo "\n\n----------------------$query\n\n";
               $msql_new  = new Db;
               $msql_new->connect();
               $msql_new->execute($query);
               $msql_new->disconnettiDB();

            }
            system("rm -rf ".$archivio_dir['dir']);
        }
        
        if(checkArchivioHasDeleted("rasponi"))
        {
            $archivio_dir=MakeWriterRasponi($start_data,$data_year_ago);
            if($archivio_dir['result'])
            {
                $file=$archivio_dir['dir'];
                chown("$file.zip",'www-data');
                chmod("$file.zip", 0777);

                $checksum = sha1($start_data.$data_year_ago."rasponi"); 
                $alarm=new Alarm();
                $alarm->SendArchivioSistem("$file.zip",$start_data,$data_year_ago,$checksum,"RASPONI");

                echo "----------------------$file\n\n";
                $query="INSERT INTO delete_dati (nome_tab,data_start,data_end,checksum,path_file) VALUES ('rasponi','$start_data','$data_year_ago','$checksum','$file.zip'); "; 
                $msql_new  = new Db;
                $msql_new->connect();
                $msql_new->execute($query);
                $msql_new->disconnettiDB();            
            }
            echo "----------------------".$archivio_dir['dir']."\n\n";
            system("rm -rf ".$archivio_dir['dir']);
        }
    }
}

function clearDatiDB()
{
    $msql  = new Db;
    $msql->connect();
    foreach (glob(PATH_DIR."/ArchivioDB/*.zip") as $filename) 
    {
	    echo "SELECT * FROM communications WHERE path_archivio= '$filename'" . "\n";
            //$arr=$msql->execute_select("SELECT * FROM communications WHERE path_archivio= '$filename'"); //data piu recente in DB
            
    }
}

function expireSetting()
{
    $DATA=date("Y-m-d G:i:00");
    $msql  = new Db;
    $msql->connect();  
    $DAY_SEC=3600 * 24 * 1;
    $arr=$msql->execute_select("SELECT ftp_date,data_scadenza,ftp_ip FROM ftp_table;"); //data piu recente in DB
    
    for($row=0;$row<count($arr);$row++)
    {
        if($arr[$row][0] != 0)
        {
           $data_sec=strtotime($arr[$row][1]);
           $diff=($data_sec- time());
           echo $diff;
           if($diff <= $DAY_SEC)
           {
               
               $txt="Le impostazioni del server: ".$arr[$row][2]." scadono il ".$arr[$row][1];
               $val=$msql->execute_select("SELECT id,text,data FROM alarm_status;");
              
               if(count($val)>0)
               {
                   $message=$val[0][1]." ".$txt;
                   $msql->execute("UPDATE alarm_status SET text='$message' where id=".$val[0][0].";");
                   echo "UPDATE alarm_status SET text='$message' where id=".$val[0][0].";";
               }
               else
                  $msql->execute("INSERT INTO alarm_status (data,text) values ('$DATA','$txt');");
                echo "INSERT INTO alarm_status (data,text) values ('$DATA','$txt');";
           }
        }
        
    }
    $msql->disconnettiDB();
}

expireSetting(); //controlla se la password e' scaduta
statusTask(); //Status da inviare messaggi
makeArchivio(); //invia archivio
clearDatiDB();
?>
